"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const auth_1 = require("../../../services/auth");
const index_1 = require("../../../store/index");
const toast_1 = require("../../../utils/toast");
const tabBar_1 = require("../../../utils/tabBar");
Page({
    data: {
        mode: "login",
        account: "",
        password: "",
        nickname: "",
        role: "chef",
        loading: false,
        remember: false,
    },
    onLoad() {
        this.restoreRemembered();
    },
    onShow() { },
    switchMode(event) {
        const mode = event.currentTarget.dataset.mode;
        this.setData({ mode, password: "" });
    },
    handleAccount(event) {
        this.setData({ account: event.detail.value.trim() });
    },
    handlePassword(event) {
        this.setData({ password: event.detail.value });
    },
    handleNickname(event) {
        this.setData({ nickname: event.detail.value.trim() });
    },
    handleRole(event) {
        this.setData({ role: event.detail.value });
    },
    handleRememberChange(event) {
        var _a;
        const value = ((_a = event.detail) === null || _a === void 0 ? void 0 : _a.value) || [];
        const remember = Array.isArray(value) && value.includes("remember");
        this.setData({ remember });
        if (!remember) {
            this.clearRemembered();
        }
    },
    handleSubmit() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.data.loading)
                return;
            const { mode, account, password, nickname, role, remember } = this.data;
            if (!account || !password) {
                (0, toast_1.toast)("请输入账号和密码");
                return;
            }
            if (mode === "register" && !nickname) {
                (0, toast_1.toast)("请输入昵称");
                return;
            }
            this.setData({ loading: true });
            try {
                let result;
                if (mode === "register") {
                    result = yield (0, auth_1.register)(account, password, role, nickname);
                    index_1.globalStore.setUserProfile(result.user);
                    this.setData({ remember: true });
                    this.saveRemembered(account, password, role);
                }
                else {
                    result = yield (0, auth_1.login)(account, password);
                    index_1.globalStore.setUserProfile(result.user);
                }
                yield index_1.globalStore.initAppData();
                if (remember || mode === "register") {
                    this.saveRemembered(account, password, role);
                }
                else {
                    this.clearRemembered();
                }
                wx.showToast({ title: "成功", icon: "success" });
                setTimeout(() => {
                    var _a;
                    const targetRole = (_a = index_1.globalStore.userProfile) === null || _a === void 0 ? void 0 : _a.role;
                    (0, tabBar_1.applyTabBar)(targetRole === "chef" ? "chef" : targetRole === "diner" ? "diner" : "guest");
                    if (targetRole === "chef") {
                        wx.switchTab({ url: "/pages/user/cart/index" });
                    }
                    else {
                        wx.switchTab({ url: "/pages/user/home/index" });
                    }
                }, 300);
            }
            catch (error) {
                console.error("auth failed", error);
                (0, toast_1.toast)(error.message || "操作失败");
            }
            finally {
                this.setData({ loading: false });
            }
        });
    },
    restoreRemembered() {
        try {
            const cached = wx.getStorageSync("cm_auth_remember");
            if (cached && cached.account && cached.password) {
                this.setData({
                    account: cached.account,
                    password: cached.password,
                    role: cached.role || "chef",
                    remember: true,
                });
            }
        }
        catch (error) {
            console.warn("restore remember failed", error);
        }
    },
    saveRemembered(account, password, role) {
        try {
            wx.setStorageSync("cm_auth_remember", { account, password, role });
        }
        catch (error) {
            console.warn("save remember failed", error);
        }
    },
    clearRemembered() {
        try {
            wx.removeStorageSync("cm_auth_remember");
        }
        catch (error) {
            console.warn("clear remember failed", error);
        }
    },
});
